package com.youyun56.gps.android;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.youyun56.gps.android.commands.CommandType;
import com.youyun56.gps.android.common.JSONKey;
import com.youyun56.gps.android.dao.ImDao;
import com.youyun56.gps.android.pojo.Im;

public class ImsHandler extends Handler {
    private ImsActivity imsActivity;
    private final static String tag = ImsHandler.class.getName();

    public ImsHandler(ImsActivity imsActivity) {
        this.imsActivity = imsActivity;
    }

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        try {
            JSONObject input = (JSONObject) msg.obj;
            switch (msg.what) {
            case CommandType.ADD_IM:
                List<Im> ims = ImsHandler.createIms(input);
                for (Im im : ims) {
                    ImDao.getInstance().saveIm(im);
                }
                imsActivity.getAdapter().addAll(ims);
                break;
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Log.e(tag, e.getMessage(), e);
        }

    }

    public final static List<Im> createIms(JSONObject input) throws JSONException {

        List<Im> ims = new ArrayList<Im>();
        if (!input.isNull("ims")) {
            JSONArray array = input.getJSONArray("ims");
            for (int i = 0; i < array.length(); i++) {
                JSONObject o = array.getJSONObject(i);
                Im im = new Im();
                im.setAddDay(o.getString("addDay"));
                im.setAttach(o.getString("attach"));
                im.setContext(o.getString("context"));
                im.setUserId(o.getLong("userId"));
                ims.add(im);
            }
            return ims;
        } else if (!input.isNull(JSONKey.IM)) {
            JSONObject o = input.getJSONObject(JSONKey.IM);
            Im im = new Im();
            im.setAddDay(o.getString("addDay"));
            im.setAttach(o.getString("attach"));
            im.setContext(o.getString("context"));
            im.setUserId(o.getLong("userId"));
            ims.add(im);
        } else {
            return Collections.EMPTY_LIST;
        }
        return ims;

    }

    public final static Im getIm(JSONObject o) throws JSONException {
        Im im = new Im();
        im.setAddDay(o.getString("addDay"));
        im.setAttach(o.getString("attach"));
        im.setContext(o.getString("context"));
        im.setUserId(o.getLong("userId"));
        return im;
    }

}
